#import "SEGLoginV2Manager.h"

#define kNSUserDefaultsUserId @"seg_USERID"
#define kNSUserDefaultsUserTel @"seg_TEL"
#define kNSUserDefaultsUserPassword @"seg_PWD"
#define kNSUserDefaultsLoginType @"seg_LOGINTYPE"
#define kNSUserDefaultsSignOutStatus @"seg_SignOutStatus"
#define kNSUserDefaultsIsManualLoginOut @"seg_isManalLoginOut" // 是否手动退出标志位

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

#if __has_include(<Commom/SEGHTTPBusinessManager.h>)
#import <Commom/SEGHTTPBusinessManager.h>
#else
#import "SEGHTTPBusinessManager.h"
#endif

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

#if __has_include(<Commom/SEGEncryptRule.h>)
#import <Commom/SEGEncryptRule.h>
#else
#import "SEGEncryptRule.h"
#endif

#if __has_include(<SEGPlatform/SEGPlatformManager.h>)
#import <SEGPlatform/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

static id _loginManager;
static dispatch_once_t onceToken;

@implementation SEGLoginV2Manager
#pragma mark - SINGLE----BEGIN----
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _loginManager = [[self alloc] init];
    });
    return _loginManager;
}

+(void)destroyResource{
    onceToken = 0;
    _loginManager = nil;
}

#pragma mark - SINGLE----END----

#pragma mark - HTTP----BEGIN----


/**
 用户登录接口(需要验证码的)
 
 @param tel 手机号
 @param password 密码
 @param imgCode 用户输入的验证码
 @param randomToken 验证码标识
 @param loginType 登陆类型：1：手机号密码登陆，2：短信验证码登陆，3：自动登陆
 @param finished 回调
 */
- (void)requestLoginByTel:(NSString *)tel
                 password:(NSString *)password
                  imgCode:(NSString *)imgCode
              randomToken:(NSString *)randomToken
                loginType:(NSString *)loginType
                 finished:(void (^)(BOOL, id, NSString *, NSString *))finished
{
    
    NSMutableDictionary* params = [@{
                                     @"tel" : tel
                                     } mutableCopy];
    // 密码登录时，对密码进行加密
    NSString *encryPassword;
    
    [[SEGHTTPManager sharedNetworkManager] removeCookies];
    encryPassword = [SEGEncryptRule encryptByRsaWithString:password];
    
    if (encryPassword.length > 0) {
        params[@"password"] = encryPassword;
    }
    if (imgCode.length > 0) {
        params[@"imgCode"] = imgCode;
    }
    if (randomToken.length > 0) {
        params[@"randomToken"] = randomToken;
    }

    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/authc-restapi/v1/user/auth/login",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        
        if (!isSuccessed || result == nil) {
            finished(NO, nil, codeType, error.localizedDescription);
            return;
        }

        if (![result isKindOfClass:[NSDictionary class]]) {
            finished(NO, nil, codeType, error.localizedDescription);
            return;
        }

        self.login = [SEGLoginModel yy_modelWithJSON:result];
        
        /*
         登录成功：保存账号密码
         */
        if (loginType && [loginType isEqualToString:@"2"]) {
            // 使用验证码登录时，新账号和本地账号不一致时，需要清除本地密码
            NSString *oldTel = [SEGLoginV2Manager segUserTelFromLocal];
            if (![oldTel isEqualToString:tel]) {
                [SEGLoginV2Manager segSaveUserPasswordToLocal:@""];
            }
        } else {
            // 账号密码登录 需要保存密码到本地
            [SEGLoginV2Manager segSaveUserPasswordToLocal:password];
        }
        // 无论什么方式登录，都保存手机号
        [SEGLoginV2Manager segSaveUserTelToLocal:tel];
        
        finished(YES, result, codeType, error.localizedDescription);
        return;
    }];
}

// 退出登陆
-(void)requestLogOutCompleted:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{

    // 退出登录的时候不清除Cookie，在登录的时候会去清除
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v3/userApp/logout.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        completed(isSuccessed,result,codeType,error.localizedDescription);
    }];
}
#pragma mark - HTTP----END----

#pragma mark - GETTER----BEGIN----
-(SEGLoginModel *)login{
    if (!_login) {
        _login = [[SEGLoginModel alloc]init];
    }
    return _login;
}

#pragma mark - 对个人资料信息的网络请求和本地缓存操作
/**
 * 获取本地的用户手机号
 * @author Sam
 */
+(NSString*)segUserTelFromLocal{
    NSString *tel = ValueToString([[NSUserDefaults standardUserDefaults] valueForKey:kNSUserDefaultsUserTel]);
    if (!tel || tel.length == 0) {//防止老版本升级过来取不到
        tel = ValueToString([[NSUserDefaults standardUserDefaults] valueForKey:@"seg_USERNAME"]);
    }
    return tel;
}
/**
 * 保存本地的用户手机号
 * @author Sam
 */
+(void)segSaveUserTelToLocal:(NSString*)tel{
    [[NSUserDefaults standardUserDefaults] setObject:ValueToString(tel) forKey:kNSUserDefaultsUserTel];
}

/**
 * 获取本地的用户密码
 * @author Sam
 */
+(NSString*)segUserPasswordFromLocal{
    return ValueToString([[NSUserDefaults standardUserDefaults] valueForKey:kNSUserDefaultsUserPassword]);
}

/**
 * 保存本地的用户手机号
 * @author Sam
 */
+(void)segSaveUserPasswordToLocal:(NSString*)password{
    //保存用户名和密码到本地
    [[NSUserDefaults standardUserDefaults] setObject:ValueToString(password) forKey:kNSUserDefaultsUserPassword];
}

/**
 * 获取本地的登录类型
 * @author Wendy
 */
+(NSString*)segLoginTypeFromLocal{
    return ValueToString([[NSUserDefaults standardUserDefaults] valueForKey:kNSUserDefaultsLoginType]);
}

/**
 * 保存登录类型到本地
 * @author Wendy
 */
+(void)segSaveLoginTypeToLocal:(NSString*)loginType{
    //保存登录类型到本地
    [[NSUserDefaults standardUserDefaults] setObject:ValueToString(loginType) forKey:kNSUserDefaultsLoginType];
}

/// 保存退出登录状态， YES: 退出； NO：登录
/// @param isSignOut 是否退出登录
+ (void)seg_saveSignOutStatus:(BOOL)isSignOut {
    [[NSUserDefaults standardUserDefaults] setBool:isSignOut forKey:kNSUserDefaultsSignOutStatus];
}

/// 获取 “是否退出登录” 状态， YES：退出登录； NO：登录中
+ (BOOL)seg_getSignOutStatus {
    return [[NSUserDefaults standardUserDefaults] boolForKey:kNSUserDefaultsSignOutStatus];
}

/// 保存用户手动退出登录状态
/// @param isLoginOut  YES:退出登录   NO: 登录
+ (void)seg_saveUserLoginOutStatus:(BOOL)isLoginOut {
    [[NSUserDefaults standardUserDefaults] setBool:isLoginOut forKey:kNSUserDefaultsIsManualLoginOut];
}

/// 获取用户手动退出登录状态  YES:退出登录   NO: 登录
+ (BOOL)seg_getUserLoginOutStatus {
    return [[NSUserDefaults standardUserDefaults] boolForKey:kNSUserDefaultsIsManualLoginOut];
}

#pragma mark - GETTER----END----
@end
